/**
 * Created by acmen on 16-1-7.
 */
(function (angular) {
  _model.controller("myFirstController", function ($scope, $rootScope, $ionicSideMenuDelegate, $ionicHistory, $ionicTabsDelegate, $http, $state, $ionicPopup, $location, $ionicLoading, $ionicPlatform, fileReader, addressService) {
    $("#submit_btn").on('click', function () {
      var username = $("#username").val();
      var tel = $("#tel").val();
      var idcard = $("#idcard").val();
      var city = $("#city").val();
      var address_detail = $("#address_detail").val();

      if (username == "" || username == null || username == undefined || tel == "" || tel == null || tel == undefined || idcard == "" || idcard == null || idcard == undefined || city == "" || city == null || city == undefined || address_detail == "" || address_detail == null || address_detail == undefined) {
        mui.alert('请将信息填写完整', '温馨提示');
        return;
      }
      var accountId = localStorage.getItem("id");
      //提交
      var params = {
        accountId: accountId,
        username: username,
        tel: tel,
        idcard: idcard,
        city: city,
        address_detail: address_detail
      };
      addressService.addAddress(params, function (data) {
        if (data && data.code == 0) {
          //保存成功 后保存到本地  跳转到收货列表
          localStorage.setItem("address_info", JSON.stringify(params));
          mui.alert('添加成功', '温馨提示', function () {
            mui.openWindow({
              url: './address_list.html?page=1'
            });
          });

        } else {
          mui.alert("保存失败" + data.msg, "温馨提示");
        }
      });
    });
    $scope.deleteAddress = function (id) {
      var this_item = $(this);
      var btnArray = ['否', '是'];
      mui.confirm('确认删除吗？', '温馨提示', btnArray, function (e) {
        if (e.index == 1) {
          //是
          console.info(id);
          addressService.deleteAddress(id, function (data) {
            //执行成功
            if (data.code == 0) {
              $("#" + id).parent().parent().remove()
            } else {
              mui.alert("删除失败:" + data.msg, "温馨提示");
            }
          });
        } else {
          //否
        }
      })
    };

    $(".add").on("click", function () {
      //跳转到新增收货地址页面
      window.location.href = "./address_add.html?page=2";
    });
    //返回按钮
    $(".mui-pull-left").on("click", function () {
      mui.openWindow({
        url: "./address_list.html?page=1"
      });
    });
    $(".back-address-list").on("click", function () {
      mui.openWindow({
        url: "./order_goods.html"
      });
    });

    //加载地址列表
    $scope.getAddressList = function () {
      var accountId = localStorage.getItem("id");
      var param = {
        accountId: accountId
      };
      addressService.getAddressList(param, function (data) {
        if (data && data.code == 0) {
          $scope.addressList = data.data;
        } else {
          mui.alert("服务器端错误" + data.msg, "温馨提示");
        }
      });

    };


    $scope.selectAddress = function (item) {
      localStorage.setItem("address_info", JSON.stringify(item));
      //修改当前收货地址 跳转页面
      mui.openWindow({
        url: './order_goods.html'
      });

    };


    //获取page
    var pageId = addressService.queryString("page");
    if (pageId && pageId == 1) {
      //地址列表页
      $scope.getAddressList();
    }



  }).controller("SuggestionDetailCtrl", function ($scope, $rootScope, $location, suggestionService) {

    var id = myUtil.queryString("id");

    $scope.goback = function(){
      mui.openWindow({
        url:'./suggestion_list.html'
      });
    };
    
    $scope.suggestion_detail = {};
    $scope.images = [];
    suggestionService.getSuggestionDetail(id, function (data) {
      if (data.code == 0) {
        var imageStr = data.data.images;
        var imageArray = [];
        $scope.suggestion_detail = data.data;
        $scope.suggestion_detail.create_time = moment(data.data.create_time).format("YYYY年MM月DD日 HH时mm分");
        
        $scope.suggestion_detail.update_time = moment(data.data.update_time).format("YYYY年MM月DD日 HH时mm分");
        
        //将服务器返回的图片进行分割
        if(imageStr && imageStr.length >0){
          //有图片
          imageArray = imageStr.split(",");
        }

        for (var i in imageArray) {
          imageArray[i] = API_HOST + "/api" + imageArray[i];
        }

      } else if (data.code == 100 || data.code == 1015 || data.code == 1016 || data.code == 1017) {
        window.location.href = "../login.html";
      }
    })

    $scope.cancelSuggestion = function (id) {
      console.log(id);
      $scope.showConfirm = function () {
        var confirmPopup = $ionicPopup.confirm({
          title: '提  示',
          template: '是否确认撤销该意见?',
          cancelText: '取消',
          okText: '确定'
        });
        confirmPopup.then(function (res) {
          if (res) {
            console.log('You are sure');
            $state.go("core", []);

            $http({
              url: API.SUGGESTIONCANCEL + "/" + id + "?_t=" + (new Date().getTime()),
              params: {
                //                                token: getCache("token"),
              },
              scope: $scope,
              method: "GET",
            }).success(function (data) {
              console.log("撤销消息反馈返回： ");
              console.log(data);

              if (data.code == 0) {
                $ionicLoading.show({
                  template: '撤销成功 ！',
                  noBackdrop: true,
                  duration: 3000
                });
              } else if (data.code == 100 || data.code == 1015 || data.code == 1016 || data.code == 1017) {

                console.log("--------------------------重新登录");
                window.location.href = "./login.html";
              } else {
                $ionicLoading.show({
                  template: '撤销失败 ！',
                  noBackdrop: true,
                  duration: 3000
                });
              }

            });



          } else {
            console.log('You are not sure');
          }
        });
      };
      $scope.showConfirm();
    }

  }).controller("suggestionContr", function ($scope, $http, $rootScope, $location, suggestionService) {
    
    $("#suggestionBack").on("click",function(){
      mui.openWindow({
        url:'../index.html'
      });
    });
    
    
    //$rootScope.initStatus(3, 1, 0, "反馈");
    $scope.suggestion_list = [];
    suggestionService.getSuggestionList(function (data) {
      if (data.code == 0) {
        $scope.suggestion_list = data.datas;
        for (var i in $scope.suggestion_list) {
          var item = $scope.suggestion_list[i];
          item["createTime"] = (item["createTime"].substring(0, 10));
        }
      } else if (data.code == 100 || data.code == 1015 || data.code == 1016 || data.code == 1017) {

        window.location.href = "../login.html";
      }
    });
    //点击添加按钮
    $("#suggestion_add").on("click", function () {
      //跳转到添加意见反馈页面
      mui.openWindow({
        url: "./suggestion_add.html"
      });
    });


    $scope.openDetail = function (id, createTime) {
      //跳转到意见反馈详情
      mui.openWindow({
        url: "./suggestion_detail.html?id=" + id
      });
    }


  }).controller("SuggestionAddCtrl", function ($scope, $rootScope, $location, suggestionService) {

    $rootScope.suggestion = "";
    $rootScope.imageList_Root = [];

    $scope.value = "";
    $scope.change = function (data) {
      $scope.value = data;
      $rootScope.suggestion = data;
    }
    
    $scope.goback = function(){
      mui.openWindow({
        url:'./suggestion_list.html'
      });
    };


    $scope.commit_suggestion = function () {
      //获取意见反馈内容
      var content = $("textarea").val().trim();
      if (!content || typeof (content) == undefined) {
        //内容为空
        mui.alert("请输入您意见或建议", "提示");
        return;
      }

      var btnArray = ["否", "是"];
      mui.confirm("确认提交该意见吗?", "提示", btnArray, function (e) {
        if (e.index == 1) {
          var spinner = myUtil.startLoading("add_dom");
          suggestionService.commitSuggestion(content, function (data) {
            if (data.code == 0) {
              myUtil.stopLoading(spinner);
              mui.alert("提交成功,我们将尽快对您的反馈进行处理", "提示", function () {
                mui.openWindow({
                  url: "./suggestion_list.html"
                });
              });
            } else if (data.code == 1015 || data.code == 1016 || data.code == 1017) {
              myUtil.stopLoading(spinner);
              window.location.href = "../login.html";
            } else {
              myUtil.stopLoading(spinner);
              mui.alert("请检查您的网络", "提示");
            }
          });
        }
      });



    };

    $scope.handleFiles = function (ddd) {
      console.log(ddd);

    }


    $scope.imageList = [];
    $scope.add_image = function () {
      navigator.image.image("dddd");
    }
    $scope.setImageUrl = function (url) {

      $scope.imageList.push(url);
      $scope.imageList_Root.push(url);



      $scope.$apply();
    }
  }).controller("myNoticeContr", function ($scope, $rootScope, $location, myNoticeService) {

    var notice_id = myNoticeService.queryString("notice_id") * 1;
    var notice_status = myNoticeService.queryString("notice_status") * 1;
    
    //返回键
    $scope.goback = function(){
      mui.openWindow({
        url:'../index.html'
      });
    };

    //获取消息详情
    myNoticeService.getNoticeDetail(notice_id, notice_status, function (data) {

      if (data.status == "success" && data.code == 0) {
        $scope.html = data.msg;
        //$(".notice_cotent").html;
      } else if (data.code == 100 || data.code == 1015 || data.code == 1016 || data.code == 1017) {
        window.location.href = "../login.html";
      }
    });


  }).controller("myOrderContr", function ($scope, $http, $rootScope, $location, myOrderService) {
    //订单控制器
    $rootScope.priceNum = 0;

    $scope.IMAGE_IP = API_HOST;
    //获取订单数据
    $scope.add_goods = JSON.parse(localStorage.getItem("order_goods"));
    $rootScope.shop_list = $scope.add_goods; //设置全局，用于跳转添加

    $scope.goods_sum = 0;
    $scope.goods_num = 0;

    //点击新增地址信息
    $(".add_address").on('click', function () {
      window.location.href = "./address_list.html?page=1";
    });

    //点击切换地址信息
    $(".change_address").on('click', function () {
      window.location.href = "./address_list.html?page=1";
    });

    //点击返回
    $(".order-goods-back").on('click', function () {
      //跳转到首页
      //清空本地订单
      localStorage.setItem("order_goods", "");
      window.location.href = "../index.html";
    });
    //从本地获取地址信息
    $scope.address_info = JSON.parse(localStorage.getItem("address_info"));
    $scope.hasAddress = false;
    if ($scope.address_info && $scope.address_info != "") {
      $scope.hasAddress = true;
    }
    $scope.go_order_goods = function () {
      mui.openWindow({
        url: "./order_goods.html"
      });
    }


    $scope.flash_price = function () {
      $scope.goods_sum = 0;
      $scope.goods_num = 0;
      for (var key in $scope.add_goods) {
        if ($scope.add_goods[key]) {
          $scope.goods_sum += (parseFloat($scope.add_goods[key]["goodsPrice"]) * $scope.add_goods[key]["add_num"]);
          $scope.goods_sum = parseFloat($scope.goods_sum.toFixed(2));
          $scope.goods_num += parseFloat($scope.add_goods[key]["add_num"]);
        }
      }

      $scope.goods_sum = parseFloat($scope.goods_sum);
      $scope.goods_num = parseFloat($scope.goods_num);

      $rootScope.priceNum = $scope.goods_num;
    };
    $scope.flash_price();

    $scope.minus_goods_fun = function (index) {
      if ($scope.add_goods[index]["add_num"] <= 1) {
        $scope.showConfirm = function () {

          alertify.confirm('提  示', '是否删除该商品?', function () {
            delete $scope.add_goods[index];
            if (Object.keys($scope.add_goods).length == 0) {
              $ionicLoading.show({
                template: '购物车无产品，点击 添加 增加商品！',
                noBackdrop: true,
                duration: 3000
              });
            }
            $scope.flash_price();
          }, function () {
            //nothing
          });

        };
        $scope.showConfirm();
        return;
      }
      $scope.add_goods[index]["add_num"] -= 1;
      $scope.flash_price();

    };

    $scope.add_goods_fun = function (index) {
      $scope.add_goods[index]["add_num"] += 1;
      $scope.flash_price();
    };
    $scope.blur_num = 0;
    $scope.blur = function (index) {
      $scope.blur_num = $scope.add_goods[index]['add_num'];
      if (isNaN($scope.blur_num)) {
        $scope.blur_num = 1;
        //                $("#blur_input" + goods_id).text("0");
      }
      if ($scope.blur_num == "" || parseInt($scope.blur_num) < 0) {
        $scope.blur_num = 1;
      }
      if (parseInt($scope.blur_num) > 999999) {
        $scope.blur_num = 999999;
        $ionicLoading.show({
          template: '该商品的最大采购量为 999999 ！',
          noBackdrop: true,
          duration: 3000
        });
      }
      $scope.blur_num = parseInt($scope.blur_num);


      if ($scope.blur_num <= 0 || $scope.blur_num == "0") {
        $scope.showConfirm = function () {

          alertify.confirm('提  示', '是否删除该商品?', function () {
            delete $scope.add_goods[index];
            if (Object.keys($scope.add_goods).length == 0) {
              $ionicLoading.show({
                template: '购物车无产品，点击 添加 增加商品！',
                noBackdrop: true,
                duration: 3000
              });
            }
            $scope.flash_price();
          }, function () {
            //nothing
          });

        };
        $scope.showConfirm();
      }

      $scope.add_goods[index]["add_num"] = $scope.blur_num;
      $scope.flash_price();
    }


    $scope.commitData = function () {

      //获取当前收货地址
      var address_info = JSON.parse(localStorage.getItem("address_info"));
      if (!address_info || address_info == null || address_info == undefined) {
        //收货地址为空 提示用户
        mui.alert("请选择收货地址", "警告");
        return;
      }

      var btnArray = ['否', '是'];
      mui.confirm('确认下单?', '温馨提示', btnArray, function (e) {
        if (e.index == 1) {
          //是
          var post_data = [];

          for (var i in $scope.add_goods) {
            var item = $scope.add_goods[i];
            if (item.add_num != 0) {
              post_data.push({
                "id": item.id,
                "num": item.add_num,
                "addressId": address_info.id
              });
            }
          }
          if (post_data.length == 0) {
            mui.alert("您没有选择商品,不能提交哦", "提示");
            return;
          } else {
            var spinner = myUtil.startLoading("order_goods");
            $http({
              url: API.COMMITORDER + "?_t=" + (new Date().getTime()),
              method: 'POST',
              params: {
                data: JSON.stringify(post_data)
              },
              headers: {
                "X-Security-Token": getCache("token"),
              },

            }).success(function (data) {

              if (data.code == 0) {
                myUtil.stopLoading(spinner);
                mui.toast('提交成功');
                setTimeout(function () {
                  mui.openWindow({
                    url: "./order_list2.html"
                  });
                }, 1000);


              } else if (data.code == 100 || data.code == 1015 || data.code == 1016 || data.code == 1017) {

                window.location.href = "../login.html";

              } else {
                myUtil.stopLoading(spinner);
                mui.toast('提交失败，请重试');
              }

            }).error(function () {
              var spinner = myUtil.startLoading("order_goods");
              mui.alert('网络连接失败');
              myUtil.stopLoading(spinner);
            });
          };
        } else {
          //否
        }
      })


    };
  }).controller("orderDetailContr", function ($scope, $http, $rootScope, $location, orderDetailService) {

    var id = orderDetailService.queryString("id");
    //查询订单详情
    orderDetailService.getOrderDetail(id, function (data) {
      console.info(data);
      $scope.address = data.address;
      $scope.order_goods = data.data;
      $scope.goodsAmount = data.goodsAmount;
      $scope.IMAGE_IP = API_HOST;
      $scope.id = id;

    });

    //返回按钮
    $("[type=button]").on("click", function () {
      //跳转到我的订单列表页面
      mui.openWindow({
        url: "./order_list2.html"
      });
    });


  }).controller("regContrl", function ($scope, $http, $rootScope, regService) {

    $scope.register = function () {
      //获取表单信息
      var userId = $("#account").val();
      var user_name = $("#user_name").val();
      var password = $("#password").val();
      var password_confirm = $("#password_confirm").val();
      var email = $("#email").val();

      if (userId == "" || userId == undefined || userId == null) {
        mui.alert("请输入账号", "提示");
        return;
      }
      if (user_name == "" || user_name == undefined || user_name == null) {
        mui.alert("请输入您的昵称", "提示");
        return;
      }
      if (password == "" || password == undefined || password == null) {
        mui.alert("请输入密码", "提示");
        return;
      }
      if (password_confirm == "" || password_confirm == undefined || password_confirm == null) {
        mui.alert("请输入确认密码", "提示");
        return;
      }
      if (email == "" || email == undefined || email == null) {
        mui.alert("请输入您的邮箱", "提示");
        return;
      }

      //判断密码和重复密码是否一致
      if (password != password_confirm) {
        //不一致
        mui.alert("您输入的两次密码不一致", "提示");
        return;
      }
      //开始注册
      var accountInfo = {
        userId: userId,
        password: password,
        email: email,
        user_name: user_name
      }
      regService.register(accountInfo, function (data) {
        //调用服务器成功回调
        if (data.code == 0) {
          //注册成功
          mui.toast("注册成功");
          //将用户名密码保存到localstorage中
          localStorage.setItem("userId", userId);
          localStorage.setItem("userpassword", password);
          //跳转到登录界面
          mui.openWindow({
            url: "../login.html"
          });
        } else {
          mui.alert(data.msg, "提示");
        }
      });
    }
    jQuery(".mui-action-back").on("click", function () {
      //点击返回 跳转到登录界面
      mui.openWindow({
        url: "../login.html"
      });
    });



  }).controller("orderListContr", function ($scope, $http, $rootScope, $location, myOrderService) {

    // $rootScope.initStatus(3, 0, 0, "订单");
    $scope.pageNumEvent = 6;

    $scope.pageNow = 1;
    $scope.orderData = [];
    $scope.pageNum = 0;
    $scope.hasMore = true;
    $scope.cacheStatus = $rootScope.orderStatusId;

    $scope.goback = function(){
      mui.openWindow({
        url:'../index.html'
      });
    }
    
    $scope.order_type = [];
    for (var i = 0; i < 4; i++) {
      $scope.order_type[i] = "background-color:#fff;color:#29b6f6;";
    }
    $scope.order_type[$rootScope.indexOrder] = "background-color:#29b6f6;color:#fff;";

    $rootScope.indexOrder = 0;
    $rootScope.orderStatusId = 2;
    //***************  加载页面
    $scope.loadData = function (orderStatus, callback, pageNow) {
      if (typeof (orderStatus) == "undefined") {
        orderStatus = 2;
      }

      $scope.pageNum = 1;
      if (pageNow) {
        $scope.pageNum = pageNow;
      }

      $http({
        url: API.ORDERLIST + "?_t=" + (new Date().getTime()),
        params: {
          page_num: $scope.pageNum,
          page_size: $scope.pageNumEvent,
          status: orderStatus,
        },
        headers: {
          "X-Security-Token": getCache("token"),
        },
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        scope: $scope,
        method: "GET"
      }).success(function (data) {

        if (data.status == "success" && data.code == 0) {
          if (data.data.length != $scope.pageNumEvent) {
            $scope.hasMore = false;
          } else {
            $scope.hasMore = true;
          }
          for (var i in data.data) {
            var item = data.data[i];
            var classStatus = "";
            var status_str = "";
            var button_status = "- - -";
            if (item.orderStatus == -1) {
              classStatus = "gray";
              status_str = "已取消";
              button_status = "- - -";
            } else if (item.orderStatus == 1) {
              classStatus = "orange";
              status_str = "未发货";
              button_status = "取消订单";
            } else if (item.orderStatus == 2) { /****************nopay****/
              classStatus = "orange";
              status_str = "待收货";
              button_status = "确认收货";
            } else if (item.orderStatus == 3) { /****************failexamine****/
              classStatus = "gray";
              status_str = "已取消";
              button_status = "- - -";
            } else if (item.orderStatus == 4) {
              classStatus = "gray";
              status_str = "待发货";
              button_status = "- - -";
            } else if (item.orderStatus == 5) { /****************failpay****/
              classStatus = "orange";
              status_str = "付款失败";
              if (getCache("DeviceInfo") == "wangpos") {
                button_status = "付 款";
              } else {
                button_status = "- - -";
                classStatus = "gray";
              }
            } else if (item.orderStatus == 6) {
              classStatus = "orange";
              status_str = "待收货";
              button_status = "收 货";
            } else if (item.orderStatus == 7) {
              classStatus = "gray";
              status_str = "已完成";
              button_status = "- - -";
            } else if (item.orderStatus == 8) {
              classStatus = "gray";
              status_str = "付款中";
              button_status = "- - -";
            }

            var pictures = [];
            if (item.shopOrderGoods.length >= 3) {
              for (var k = 0; k < 3; k++) {
                pictures[k] = API_HOST + "/api/" + item.shopOrderGoods[k].picture;
              }
            } else {
              for (var k in item.shopOrderGoods) {
                pictures[k] = API_HOST + "/api/" + item.shopOrderGoods[k].picture;
              }
            }


            $scope.orderData[parseInt(($scope.pageNum - 1) * $scope.pageNumEvent) + parseInt(i)] = {
              id: parseInt(parseInt(i) + parseInt($scope.pageNumEvent * ($scope.pageNum - 1))),
              commitId: item.id,
              orderNum: item.orderNum,
              createTime: item.createTime,
              orderStatus: item.orderStatus,
              goodsNum: item.shopOrderGoods.length + "个商品",
              goodsSum: item.goodsAmount,
              pictures: pictures,
              classStatus: classStatus,
              status_str: status_str,
              button_status: button_status,
            }

          }
          if (callback) {
            callback(data.data);
          }
        } else if (data.code == 100 || data.code == 1015 || data.code == 1016 || data.code == 1017) {

          window.location.href = "../login.html";

        }



      });
      $scope.$broadcast('scroll.infiniteScrollComplete');
    }
    $scope.loadData();

    mui.init();
    (function ($) {

      //阻尼系数
      var deceleration = mui.os.ios ? 0.003 : 0.0009;
      $('.mui-scroll-wrapper').scroll({
        bounce: false,
        indicators: true, //是否显示滚动条
        deceleration: deceleration
      });
      $.ready(function () {
        //循环初始化所有下拉刷新，上拉加载。
        $.each(document.querySelectorAll('.mui-slider-group .mui-scroll'), function (index, pullRefreshEl) {
          $(pullRefreshEl).pullToRefresh({
            down: {
              callback: function () {
                var self = this;
                //刷新 所有 重新load
                //获取当前订单状态
                var order_status = jQuery(".mui-active").attr("app-data") * 1;
                $scope.loadData(order_status, function (data) {
                  self.endPullDownToRefresh();
                });

              }
            },
            up: {
              callback: function () {
                var self = this;
                //加载更多
                $scope.pageNow++;
                var order_status = jQuery(".mui-active").attr("app-data") * 1;
                $scope.loadData(order_status, function (data) {
                  if (data && data.length == 0) {
                    $scope.pageNow--;
                    //没有更多了
                    if ($scope.pageNow <= 1) {
                      jQuery(".mui-pull-bottom-tips").remove();
                    } else {
                      jQuery(".mui-pull-bottom-tips").text("没有更多了..");
                    }


                  } else {
                    //将获取的下一页数据append到后面
                    if (data) {
                      for (var item in data) {
                        //绘制item
                        var ul = jQuery("<ul>", {
                          class: 'mui-table-view',
                          style: 'border-bottom: 1px solid #ddd'
                        });
                        var li = jQuery("<li>", {
                          class: 'mui-table-view-cell mui-media'
                        });
                        var create_time = jQuery("<span> ng-bind='item.createTime'", {
                          style: 'float: left;padding-left:1em'
                        });
                        var status_str = jQuery("<span>", {
                          style: "float: right;padding-right:1em;color:{{item.classStatus}}",
                          text: "{{item.status_str}}"
                        });
                        var time_status_div = jQuery("<div>");
                        time_status_div.append(create_time).append(status_str);

                        var goods_num = jQuery("<div>", {
                          class: "mui-media-body",
                          style: "text-align: right;"
                        });

                        var total = jQuery("<span>", {
                          style: "float:left;line-height:2.5em;font-size:1.2em;padding-left:1em;",
                          text: "合计:"
                        });
                        var total_num = jQuery("<span>", {
                          style: "color:#ffaa33;",
                          text: "￥{{item.goodsSum}}"
                        });
                        total.append(total_num);
                        var button = jQuery("<span>", {
                          class: "button_css",
                          text: "{{item.button_status}}"
                        });

                        var total_div = jQuery("<div>");
                        total_div.append(total).append(button);
                        var total_a = jQuery("<a>");
                        total_a.append(total_div);

                        li.append(time_status_div).append(total_a);
                        ul.append(li);

                        //jQuery(".mui-table-view:last").appendChild(ul);
                      }
                    }

                  }
                  self.endPullUpToRefresh();
                }, $scope.pageNow)
              }
            }
          });
        });

      });
    })(mui);


    //*******************  tab切换
    $scope.indexOrder = 0;
    $scope.orderStatusId = 2;


    $rootScope.changeOrderStatus = function (index, orderStatus) {
      $scope.indexOrder = index;
      $scope.orderStatusId = orderStatus;

      $scope.orderData = [];
      $scope.pageNow = 1;
      $scope.loadData(orderStatus);
      $scope.hasMore = true;
      $scope.cacheStatus = orderStatus;
    }

    //*************** 进入详细页
    $scope.openDetail = function (id) {
      //进入订单详情
      mui.openWindow({
        url: './order_detail.html?id=' + id
      });
    }

    //*************** buttonClick
    $scope.commitButton = function (id) {
      var orderStatus = $scope.orderData[id].orderStatus;
      var tabStatus;
      var tabIndex;
      if (orderStatus == -1 || orderStatus == 3 || orderStatus == 7) {
        tabIndex = 3;
        tabStatus = 1;
      } else if (orderStatus == 1) {
        tabIndex = 0;
        tabStatus = 2;
      }
      if (orderStatus == 2 || orderStatus == 8 || orderStatus == 5) {
        tabIndex = 1;
        tabStatus = 3;
      }
      if (orderStatus == 4 || orderStatus == 6) {
        tabIndex = 2;
        tabStatus = 4;
      }

      var orderId = $scope.orderData[id].commitId;

      if (orderStatus == -1 || orderStatus == 3 || orderStatus == 4 || orderStatus == 7 || orderStatus == 8) {
        return;
      } else if (orderStatus == 1) {

        //取消订单
        var btnArray = ['否', '是'];
        mui.confirm('确认要取消订单吗？', '温馨提示', btnArray, function (e) {
          if (e.index == 1) {
            //是
            $http({
              url: API.ORDERCANCEL + "?_t=" + (new Date().getTime()),
              params: {
                //                                    token: getCache("token"),
                id: orderId,
              },
              scope: $scope,
              method: 'POST',
              headers: {
                "X-Security-Token": getCache("token")
              },
              contentType: "application/x-www-form-urlencoded; charset=utf-8",
            }).success(function (data) {
              if (data.status == "success" && data.code == 0) {
                $rootScope.changeOrderStatus(tabIndex, tabStatus);
              } else if (data.code == 100 || data.code == 1015 || data.code == 1016 || data.code == 1017) {

                window.location.href = "../login.html";

              }
            });
          } else {
            //否
          }
        })

      } else if (orderStatus == 2 || orderStatus == 5) {
        //付款
        var btnArray = ['否', '是'];
        mui.confirm('确认要取消订单吗？', '温馨提示', btnArray, function (e) {
          if (e.index == 1) {
            //是
            $http({
              url: API.PAYSTART + "?_t=" + (new Date().getTime()),
              params: {
                //                                    token: getCache("token"),
                id: orderId,
              },
              scope: $scope,
              method: "POST",
              headers: {
                "X-Security-Token": getCache("token")
              },
              contentType: "application/x-www-form-urlencoded; charset=utf-8",
            }).success(function (data) {
              if (data.code == 0) {
                var payData = {
                  id: orderId,
                  attach: data.data.attach,
                  body: data.data.body,
                  channel: data.data.channel,
                  notify_url: data.data.notify_url,
                  out_trade_no: data.data.out_trade_no,
                  total_fee: data.data.total_fee,
                };

                $rootScope.changeOrderStatus(tabIndex, tabStatus);
                navigator.pay.pay(JSON.stringify(payData));

              } else if (data.code == 100 || data.code == 1015 || data.code == 1016 || data.code == 1017) {

                window.location.href = "../login.html";

              } else {
                mui.alert('该订单暂不能付款!', '温馨提示');
              }


            });

          } else {
            //否
          }
        });

      } else
      if (orderStatus == 6) {
        //收货
        var btnArray = ["否", "是"];
        mui.confirm("确认收到该订单?", "提示", function (e) {
          if (e.index == 1) {
            console.log('You are sure');
            $http({
              url: API.ORDERRECEIVED + "?_t=" + (new Date().getTime()),
              params: {
                //                                    token: getCache("token"),
                id: orderId,
              },
              scope: $scope,
              method: 'POST'
            }).success(function (data) {
              console.log("订货单收货接口返回：");
              console.log(data);

              if (data.status == "success" && data.code == 0) {
                $rootScope.changeOrderStatus(tabIndex, tabStatus);
              } else if (data.code == 100 || data.code == 1015 || data.code == 1016 || data.code == 1017) {

                window.location.href = "../login.html";

              }
            });
          }
        });
      }

    }
  });

})(window.angular);